<!--
 * @Description:
 * @Author: william
 * @Date: 2024-04-15 10:36:50
 * @LastEditors: william
 * @LastEditTime: 2025-05-12 10:18:32
-->
<template>
  <el-input v-if="hasDefaultSlot" ref="refInput" v-model="modelValue" :placeholder="getPlaceholder()"
    :maxlength="maxlength" :clearable="!verifyType && clearable" :="$attrs" @input="handleInput">
    <template #prefix>
      <slot name="prefix" />
    </template>
    <template #suffix>
      <slot name="suffix" />
    </template>
    <!-- <template #prepend>
      <slot name="prepend" />
    </template>
    <template #append>
      <slot name="append" />
    </template> -->
  </el-input>
  <el-input v-else ref="refInput" v-model="modelValue" :placeholder="getPlaceholder()" :maxlength="maxlength"
    :clearable="!verifyType && clearable" :="$attrs" @input="handleInput" />
</template>

<script setup>
const props = defineProps({
  verifyType: {
    type: String,
    default: '' // nzint-不以0开头的整数/int-整数/float-浮点数/alnum-字母或数字[a-zA-Z0-9]/idcard-身份证号/all-正数负数0
  },
  maxlength: {
    type: Number,
    default: 128
  },
  clearable: {
    type: Boolean,
    default: true
  },
  placeholder: {
    type: String,
    default: ''
  },
  label: {
    type: String,
    default: ''
  }
})

const emit = defineEmits(['input'])
const modelValue = defineModel({
  type: String,
  default: ''
})
const slots = useSlots()
const refInput = ref(null)
const hasDefaultSlot = computed(() => !!slots.prefix || !!slots.suffix)

const getPlaceholder = _ => {
  return (
    props.placeholder ||
    g_rules.zhAndEnShowMsg(g_t('public.pleaseInput'), props.label)
  )
}

// 对输入的字符进行过滤
const handleInput = value => {
  // 如果是浮点数类型，需要特殊处理以支持负数
  if (props.verifyType === 'all') {
    // 移除所有非数字、小数点和负号的字符
    let cleanedValue = value.replace(/[^\d.-]/g, '')

    // 确保负号只能在开头且只有一个
    const negativeSigns = cleanedValue.match(/-/g)
    if (negativeSigns && negativeSigns.length > 0) {
      // 如果有负号，保留第一个，移除其他的
      if (cleanedValue.indexOf('-') !== 0) {
        // 如果负号不在开头，移除所有负号并在开头添加一个
        cleanedValue = '-' + cleanedValue.replace(/-/g, '')
      } else {
        // 如果负号在开头，只保留开头的负号
        cleanedValue = '-' + cleanedValue.substring(1).replace(/-/g, '')
      }
    }

    // 确保小数点只能有一个
    const parts = cleanedValue.split('.')
    if (parts.length > 2) {
      // 如果有多个小数点，只保留前两个部分，用一个小数点连接
      cleanedValue = parts[0] + '.' + parts.slice(1).join('')
    }

    modelValue.value = cleanedValue
  } else {
    // 其他类型的验证保持不变
    const verifyMap = {
      nzint: /^(0+)|[^1-9\^\d]+/g,
      int: /[^\d]+/g,
      alnum: /[^\w]+/g,
      idcard: /[^\d^A-Z]+/g,
      cletter: /[^A-Z]+/g
    }
    modelValue.value = value.replace(verifyMap[props.verifyType] || '', '')
  }

  emit('input', modelValue.value)
}

defineExpose({
  refInput
})
</script>
